<?php
namespace App\Tools;
use App\Http\Controllers\Controller;
require '../vendor/autoload.php';
// 导入 Intervention Image Manager Class
use Intervention\Image\ImageManager;
use Input;

class UploadFiles extends Controller{

	// 只允许以下后缀名的图片文件上传
    protected $allowed_ext = ["png", "jpg", "gif", 'jpeg'];

	//文件上传方法 by:hg 2017-11-04
	/**
	 * [uploads description]
	 * @param  [string] $name   [表单名字]
	 * @param  [int] $w      [裁剪宽]
	 * @param  [int] $h      [裁剪高]
	 * @param  [int] $avatar [判断是否是上传头像]
	 * @param  [int] $batch  [判断是否是批量]
	 * @return [string]      [返回上传地址]
	 */
	public function uploads($name,$w=0,$h=0,$avatar=0,$batch=-1){
		if(!Input::hasFile($name)){
			return false;
		}

		$fileObj = Input::file($name);

		//判断是否是批量上传
		if($batch>=0){
			$fileObj = $fileObj[$batch];
		}

		$type = $fileObj->getClientOriginalExtension();//获取后缀

		// 判断是否图片类型合法
		if (!in_array($type, $this->allowed_ext)) {
            return false;
        }
		$names = time().mt_rand(1000,9999);//上传改名
		$nowTime = date('Ymd');
		$nowPath = public_path().'/Uploads/'.$nowTime;
		if(!is_dir($nowPath)){
			mkdir($nowPath,0777,true);
		}
		$big = 'Uploads/'.$nowTime.'/'.$names.'.'.$type;
		$small = 'Uploads/'.$nowTime.'/'.$names.'_'.$w.'x'.$h.'.'.$type;
		$manager = new ImageManager(array('driver' => 'gd'));
		// $manager->make(Input::file($name))->save($big);
		
		// 判断是否头像
		// if(!empty($w) && !empty($h) && $avatar){
		// 	$manager->make($fileObj)->resize($w,$h,function($v){
		// 		$v->aspectRatio(); 
		// 	})->resizeCanvas($w,$h)->save($small);

		// 	$data['smallPath'] = $small;
		// }

		// 都为空直接上传，其余的上传都形成一大一小两图
		if(empty($w) || empty($h) && !$avatar){
			$manager->make($fileObj)->save($big);
			$data['bigPath'] = $big;
		}else{
			if($avatar){
				$nowPath = public_path().'/Uploads/avatar/'.$nowTime;
				if(!is_dir($nowPath)){
					mkdir($nowPath,0777,true);
				}
				$big = 'Uploads/avatar/'.$nowTime.'/'.$names.'.'.$type;
				$small = 'Uploads/avatar/'.$nowTime.'/'.$names.'_'.$w.'x'.$h.'.'.$type;
			}
			$manager->make($fileObj)->save($big);
			$manager->make($fileObj)->resize($w,$h,function($v){
				$v->aspectRatio(); 
			})->resizeCanvas($w,$h)->save($small);
			$data['smallPath'] = $small;
			$data['bigPath'] = $big;
		}


		return $data;
	}
}